package com.nbsaas.lbs.baidu.v3.service;

import com.google.gson.Gson;
import com.nbsaas.http.Connection;
import com.nbsaas.http.HttpConnection;
import com.nbsaas.utils.StringUtils;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

public abstract class BaseService {
  
  protected Config config;
  
  public BaseService(Config config) {
    this.config = config;
  }
  
  protected Connection getConnection(String url) {
    Connection connection = HttpConnection.connect(url);
    configs(connection, config);
    return connection;
  }
  
  private void configs(Connection connection, Config config) {
    connection.data("ak", config.getAk());
    if (config.getGeotable()!=null){
      connection.data("geotable_id", config.getGeotable());
    }
  }
  
  protected void buildParams(Connection connection, Map<String, String> maps) {
    if (maps!=null&&maps.size() > 0) {
      Set<String> keys = maps.keySet();
      for (String string : keys) {
        String value = maps.get(string);
        if (StringUtils.isNotBlank(value)) {
          connection.data(string, "" + value);
        }
      }
    }
  }
  
  public <T> T execute(Connection connection, Class<T> tClass) {
    T result = null;
    try {
      String msg = connection.execute().body();
      Gson gson = new Gson();
      result = gson.fromJson(msg, tClass);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return result;
  }
  public String execute(Connection connection) {
    String result = null;
    try {
      result= connection.execute().body();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return result;
  }
}
